package com.lyj.mall.realm;


import com.lyj.mall.dao.RolePermissionsMapper;
import com.lyj.mall.dao.UserMapper;
import com.lyj.mall.dao.UserRolesMapper;
import com.lyj.mall.enums.ResponseEnum;
import com.lyj.mall.pojo.RolePermissions;
import com.lyj.mall.pojo.User;
import com.lyj.mall.pojo.UserRoles;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
public class CustomRealm extends AuthorizingRealm {

    {
        super.setName("CustomRealm");
    }

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RolePermissionsMapper rolePermissionsMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        String username = user.getUsername();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 获取角色
        List<UserRoles> userRolesDOList = userRolesMapper.findUserRolesByUsername(username);
        Set<String> roleNames = new HashSet<>();
        userRolesDOList.forEach(userRole -> roleNames.add(userRole.getRoleName()));
        authorizationInfo.setRoles(roleNames);
        log.info("用户: {},的角色有: {}", username, roleNames);
        // 获取权限
        Set<String> permissions = new HashSet<>();
        roleNames.forEach(role -> {
            Set<RolePermissions> permissionsSet = rolePermissionsMapper.findPermissionsByRole(role);
            permissionsSet.forEach(permission -> {
                permissions.add(permission.getPermission());
            });
        });
        log.info("用户: {},的权限有: {}", username, permissions);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        User user = userMapper.findUserByUsername(username);
        if (user == null) {
            throw new UnknownAccountException(ResponseEnum.USERNAME_OR_PASSWORD_ERROR.getDesc());
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), "CustomRealm");

        return simpleAuthenticationInfo;
    }
}
